package edu.nwpu.controller;


import com.alibaba.fastjson.JSON;
import edu.nwpu.utils.ImageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
public class ImageController {

    private static final String IMG_URL = "http://101.132.73.96/img/oos/";

    private static final String IMG_PATH = "/usr/local/tomcat/webapps/img/oos";

//    private static final String IMG_PATH = "D:\\Desktop\\images";

    @PostMapping("/img/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> response = new HashMap<>();
        if (!file.isEmpty()) {
            try {
                if (ImageUtil.checkFileType(file)) {
                    String fileName = ImageUtil.generateFileName(file);
                    file.transferTo(new File(IMG_PATH + File.separator + fileName));//把文件写入目标文件地址
                    response.put("status", "success");
                    response.put("url", IMG_URL + fileName);
                    return JSON.toJSONString(response);
                } else {
                    response.put("info", "文件类型不正确");
                }
            } catch (Exception e) {
                response.put("info", e.getLocalizedMessage());
            }
        } else {
            response.put("info", "上传的文件为空");
        }
        response.put("status", "failed");
        return JSON.toJSONString(response);
    }

}
